/**
 * 
 * @authors cherish yii2 (cherish@cherish.pw)
 * @date    2021-07-28 12:48:28
 * @version v2.0
 * @description the core js of todolist project
 * 
 * ━━━━━━神兽出没━━━━━━
 * 　　   ┏┓　 ┏┓
 * 　┏━━━━┛┻━━━┛┻━━━┓
 * 　┃              ┃
 * 　┃       ━　    ┃
 * 　┃　  ┳┛ 　┗┳   ┃
 * 　┃              ┃
 * 　┃       ┻　    ┃
 * 　┃              ┃
 * 　┗━━━┓      ┏━━━┛ Code is far away from bugs with the animal protecting.
 *       ┃      ┃     神兽保佑,代码无bug。
 *       ┃      ┃
 *       ┃      ┗━━━┓
 *       ┃      　　┣┓
 *       ┃      　　┏┛
 *       ┗━┓┓┏━━┳┓┏━┛
 *     　  ┃┫┫　┃┫┫
 *     　  ┗┻┛　┗┻┛
 *
 * ━━━━━━感觉萌萌哒━━━━━━
 */

// 请根据考试说明文档中列出的需求进行作答
// 预祝各位顺利通过本次考试！
// ...

/**
 * 添加代办事项
 */


const title_ele = document.getElementById("title");
const todolist_ele = document.getElementById("todolist");
const donelist_ele = document.getElementById("donelist");
const section_ele = document.querySelector("section");
console.log(section_ele);
const foot = document.querySelector('footer')

// 功能1，添加待办事项
addEvent(title_ele, "keydown", function(e) {
    var keyCode = e.which || e.keyCode;
    var obj = {
        tag_name: "li",
        children: [{
            tag_name: "input",
            attributes: {
                type: "checkbox",
                class: "checkbox"
            }
        }, {
            tag_name: "p",
            content: title_ele.value
        }, {
            tag_name: "a",
            attributes: {
                href: "javascript:void(0)"
            },
            content: "-"
        }]
    }
    if (keyCode === 13) {
        console.log(title_ele.value);
        if (title_ele.value === "") {
            alert("请输入待办事项内容，再按Enter确认")
        } else {
            todolist_ele.insertBefore(createEle(obj), todolist_ele.childNodes[0]);
            title_ele.value = "";
        }
    }
})

// 功能2，完成待办事项
addEvent(todolist_ele, "change", ".checkbox", function() {
    donelist_ele.insertBefore(this.parentNode, donelist_ele.childNodes[0]);
})

// 功能3，重置已完成事项
addEvent(donelist_ele, "change", ".checkbox", function() {
    todolist_ele.insertBefore(this.parentNode, todolist_ele.childNodes[0]);
})

// 功能4，删除事项
addEvent(section_ele, "click", "a", function() {

    this.parentNode.remove();
})

// 功能5，修改事项内容
addEvent(todolist_ele, "click", "p", function() {
    var insert_html = '<input value="' + this.innerText + '">';
    this.innerHTML = insert_html;
    this.children[0].select();
    addEvent(this.children[0], "blur", function() {
        this.parentNode.innerText = this.value;

    })
    addEvent(this.children[0], "keydown", function(e) {
        var keyCode = e.which || e.keyCode;
        if (keyCode === 13) {
            this.parentNode.innerText = this.value;
        }
    })
})


// 封装创建元素的函数
function createEle(obj) {
    var node = document.createElement(obj.tag_name);
    if (obj.attributes) {
        // 若属性存在，则遍历属性添加给node
        for (var attr in obj.attributes) {
            node.setAttribute(attr, obj.attributes[attr]);
        }
    }
    if (obj.content) {
        // 若内容存在，则将内容插入节点中
        node.innerText = obj.content;
    }
    if (obj.children && obj.children.length > 0) {
        // 若子集存在，则遍历子集，递归调用createEle()
        for (var i = 0; i < obj.children.length; i++) {
            node.appendChild(createEle(obj.children[i]));
        }
    }
    return node;
}


// 封装事件委托和事件监听
function addEvent(ele, event_type, cb_or_selector, cb) {
    // 若传入的是4个参数且第三个参数是字符串，说明是添加事件委托
    if (arguments.length === 4 && typeof cb_or_selector === "string") {
        // 添加事件委托，获取事件目标
        ele.addEventListener(event_type, function(evt) {
                var e = evt || event;
                var target = e.target || e.srcElement;
                // 根据传入的字符串判断选择器类型
                switch (cb_or_selector.substr(0, 1)) {
                    case ".":
                        var selector_type = "className";
                        var selector_name = cb_or_selector.slice(1);
                        break;
                    case "#":
                        var selector_type = "id";
                        var selector_name = cb_or_selector.slice(1);
                        break;
                    default:
                        var selector_type = "nodeName";
                        var selector_name = cb_or_selector.toUpperCase();
                }
                // 封装事件冒泡逐层向上查找事件目标
                while (target !== ele) {
                    // 验证事件目标
                    if (target[selector_type] === selector_name) {
                        // 使用call改变this指向
                        cb.call(target, e);
                        break;
                    }
                    target = target.parentNode;
                }
            })
            // 若逻辑只有两种，可以使用 return false
        return false;
    }
    // 若传入三个参数，说明是添加事件监听
    ele.addEventListener(event_type, cb_or_selector);
}
const xhr = new XMLHttpRequest()
xhr.open('GET', '/aqi')

xhr.onload = function() {
    const res = JSON.parse(xhr.responseText)
    console.log(res);
    const str = `
   <p>
    您当前的ip地址是：<strong id="ipv4">${res.endip}</strong>，地理位置：<strong id="addr">${res.country}  ${res.area}</strong>
   </p>
   
    `
    foot.innerHTML += str

}
xhr.send('')